import {
  getDates,
  formatDate
} from "../../util/data.js"
import {
  databaseSearch,
  databaseAdd,
  databaseUpdate 
} from "../../util/database.js"

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    checkActionVis: false,
    menuactions: "", //弹出菜单选项
    startTime: "", //开始时间
    endTime: "", //结束时间
    startStatus: "", //开始状态 是否为今天
    allDateLength: "", //持续时间
    endTimeStart: "",
    endTimeEnd: "",
    remindVal: "仅一次", //设置提醒显示参数
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.remind = [{
        name: '提醒'
      },
      {
        name: '不提醒',
      }
    ];
    this.repeat = [{
        name: '每天',
      },
      {
        name: '仅一次',
      }
    ];
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    this.maxLen = 7;
    let time = formatDate(new Date());
    let date = getDates(1, time);
    console.log(date);
    this.startTime = date[0].time; //开始时间
    this.endTime = date[date.length - 1].time; //结束时间
    this.setData({
      startTime: date[0].time + " , " + date[0].week,
      endTime: date[0].time + " , " + date[0].week,
      startStatus: "今天",
      allDateLength: 1, //共几天
      endTimeStart: date[0].time,
      endTimeEnd: date[date.length - 1].time,
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function(e) {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  changeAction: function(e) {
    console.log(e);
    console.log(e.currentTarget.dataset.item);
    let item = e.currentTarget.dataset.item;
    if (item = "remind") {
      this.setData({
        checkActionVis: true,
        menuactions: this.remind
      })
    }
    if (item = "repeat") {
      this.setData({
        checkActionVis: true,
        menuactions: this.repeat
      })
    }
  },
  onClose: function() {
    this.setData({
      checkActionVis: false
    })
  },
  onSelect: function(e) {
    console.log(e);
    console.log(e.detail.name);
    let value = e.detail.name;
    if (value == "每天") {
      this.select = "every"
      this.setData({
        remindVal: "每天",
        checkActionVis: false
      })
    } else if (value == "仅一次") {
      this.select = "only"
      this.setData({
        remindVal: "仅一次",
        checkActionVis: false
      })
    }
  },
  setting: function() {
    var data = {
      remind_val: this.select,
      start_time: this.startTime,
      end_time: this.endTime,
      title: this.Title,
      desc: this.Desc,
      data_len: this.data.allDateLength
    }
    var timeArr = getDates(data.data_len, data.start_time);
    console.log(timeArr);
    var timeArrMap = new Map();
    let setList = [];
    // let yearArr = [];
    for (let i = 0; i < timeArr.length; i++) {
      let year = timeArr[i].time.split("-")[0];
      let month = parseInt(timeArr[i].time.split("-")[1]);
      let day = parseInt(timeArr[i].time.split("-")[2]);
      let openid = wx.getStorageSync("openid");
      let list = {
        id: Date.now().toString(),
        title: data.title,
        desc: data.desc,
        time: data.time || 0
      }
      if (!setList[month] || !setList[month][day] || !setList[month][day].list) {
        setList[month] = [];
        setList[month][day] = {};
        setList[month][day].list = [];
        setList[month][day].list.push(list);
      } else {
        setList[month][day].list.push(list);
      }
      timeArrMap.set(openid + "&&" + year, setList)
    }
    console.log(timeArrMap);
    for (let key of timeArrMap) {
      let yearArr = [key[0]];
      databaseSearch(yearArr, (res) => {
        if (res.data.length == 0) {
          // for (let i = 0; i < yearArr.length; i++) {
          let allData = {
            _id: yearArr[0],
            data: timeArrMap.get(yearArr[0])
          }
          databaseAdd(allData, (res) => {
            console.log(res);
          })
          // }
        } else {
          // console.log(5555555555555555)
          // console.log(res.data);
          let setList = res.data[0];
          let arrList = timeArrMap.get(yearArr[0]);
          for (let i = 0; i < arrList.length; i++) { // 第一层，比对月份
            if (arrList[i] != null && arrList[i].length > 0) {
              let daylen = arrList[i].length;
              for (let j = 0; j < daylen; j++) { // 第二层 比对天
                if (!!arrList[i][j] && !!arrList[i][j].list && arrList[i][j].list.length > 0) {
                  if (!!setList.data[i][j] && setList.data[i][j].list.length > 0) {
                    setList.data[i][j].list = setList.data[i][j].list.concat(arrList[i][j].list);
                  } else {
                    setList.data[i] = arrList[i];
                  }
                }
              }
            }
          }
          databaseUpdate(setList,(res) => {
            console.log(res);
            if (res.stats.updated == 2){
              app.routerTo("redirectTo", "/pages/calendar/index");
            }
          },(res) => {
            console.log(res);
            if (res.stats.updated == 2) {
              app.routerTo("redirectTo", "/pages/calendar/index");
            }
          })

        }
      });

    }
    // wx.cloud.callFunction({
    //   name: 'add_time_list',
    //   data: data
    // }).then(res => {
    //   console.log(res);
    //   if(res.result.list){
    //     console.log(res.result.list[0].data)
    //   }
    //   // output: res.result === 3
    // }).catch(err => {
    //   console.log(err);
    //   // handle error
    // })
  },
  bindStartDateChange: function(e) {
    let time = formatDate(new Date(e.detail.value));
    let date = getDates(this.maxLen, time);
    var nowDate = ""
    if (formatDate(new Date()) == time) {
      nowDate = "今天"
    }
    this.endTime = date[0].time;
    this.setData({
      startTime: date[0].time + " , " + date[0].week,
      startStatus: nowDate,
      allDateLength: 1, //共几天
      endTime: date[0].time + " , " + date[0].week,
      endTimeStart: date[0].time,
      endTimeEnd: date[date.length - 1].time,
    })
  },
  bindEndDateChange: function(e) {
    var self = this;
    let time = formatDate(new Date(self.data.startTime));
    let date = getDates(this.maxLen, time);
    var nDate = Date.parse(new Date(e.detail.value)) / 1000;
    var sDate = Date.parse(new Date(self.data.startTime.split(",")[0])) / 1000;
    var len = parseInt((nDate - sDate) / 86400) + 1;
    let weeks = getDates(1, formatDate(new Date(e.detail.value)));
    console.log(weeks);
    this.setData({
      endTime: e.detail.value + " , " + weeks[0].week,
      endTimeStart: date[0].time,
      allDateLength: len, //共几天
      endTimeEnd: date[date.length - 1].time,
    })
  },
  addTitleInput: function(e) {
    this.Title = e.detail.value;
  },
  addDescInput: function(e) {
    this.Desc = e.detail.value;
  }
})